package com.hfzy.ihk.web.linkcall.support.tts;

import com.alibaba.nls.client.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * Created by YANFA on 2018/10/22.
 */
@Component
public class CreateToken {


    private static RedisTemplate redisTemplate ;



    @Autowired
    public  void setRedisTemplate(RedisTemplate redisTemplate) {
        CreateToken.redisTemplate = redisTemplate;
    }

    private static final  String ALIYUN_TOKEN_KEY="aliyun:token";
    /**
     * token 12小时过期，将期保存在redis 设定11小时自动过期
     * @param akId
     * @param akSecrete
     * @return
     */
    public static String aliyunToken (String akId,String akSecrete){
        Boolean bl = redisTemplate.hasKey(ALIYUN_TOKEN_KEY);
        redisTemplate.delete(ALIYUN_TOKEN_KEY);
        try {
            if (bl && redisTemplate.opsForValue().get(ALIYUN_TOKEN_KEY)!=null) {
                return String.valueOf(redisTemplate.opsForValue().get(ALIYUN_TOKEN_KEY));
            }else{//不存在重新获取
                AccessToken accessToken = AccessToken.apply(akId, akSecrete);
                if(accessToken!=null&&accessToken.getToken()!=null){
                    redisTemplate.opsForValue().set(ALIYUN_TOKEN_KEY,accessToken.getToken(),60 * 60 *11L, TimeUnit.SECONDS);
                    return accessToken.getToken();
                }else{
                    return "";
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }


    }
}
